package com.adv.netWork02.loginServer;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.*;

//1:服务器上存有多个用户对象（包括用户和密码），客户端通过socket登录，如果成功，输出欢迎信息，失败给出提示。
public class LoginServer extends Thread {

	private ServerSocket s;
	private Map<String, String> map = new HashMap<String, String>();

	private LoginServer(ServerSocket s) {
		this.s = s;
		super.setName(String.valueOf(s.getInetAddress()));
		map.put("张三", "111111");
		map.put("李四", "222222");
		map.put("王五", "333333");
		map.put("王二麻", "444444");

	}

	@Override
	public void run() {
		System.out.println("-----------欢迎登陆-------------");
		boolean flag = true;// 标注退出时机
		while (flag) {
			try {
				Socket client = s.accept();
				System.out.println("客户端的信息:" + client.getInetAddress() + ",端口:" + client.getPort() + "已连接服务器");
				InputStream is = client.getInputStream();
				OutputStream os = client.getOutputStream();
				PrintWriter pw = new PrintWriter(os, true);
				ObjectInputStream oin = new ObjectInputStream(is);
				Map<String, String> temp;
				while (flag) {
					pw.println("<-请输入账号密码：->");
					temp = (Map<String, String>) oin.readObject();// 反序列化得到客户端输入的账号密码
					System.out.println("客户端<" + client.getInetAddress() + ">输入：" + temp);
					// 获取temp中账号密码
					String name = null;
					String password = null;
					Iterator<String> it = temp.keySet().iterator();
					while (it.hasNext()) {
						name = it.next();
						password = temp.get(name);
						System.out.println(name + "=>>" + password);
					}
					// 跟服务器中的账号密码作对比
					System.out.println(map);// 纠错用
					Iterator<String> it2 = map.keySet().iterator();
					int num = 0;
					String name2 = null;
					String password2 = null;
					while (it2.hasNext()) {
						System.out.println("开始对比");// 纠错用
						name2 = it2.next();
						password2 = map.get(name2);
						System.out.println("Map:" + name2 + "=>>" + password2);// 纠错用
						if (name2.equals(name)) {// 比账号
							System.out.println("名字是对的");// 纠错用
							if (password2.equals(password)) {// 比密码
								System.out.println("登录成功！");
								num = 1;// "登录成功！"
								flag = false;
								break;
							} else {
								System.out.println("登录失败，密码错误！");
								num = 2;// "登录失败，密码错误！"
							}
						} else {
							System.out.println("登录失败，账号错误！");
							num = 3;// "登录失败，账号错误！"
						}
						System.out.println(num);
					}
					if (num == 1) {
						pw.println("登录成功，欢迎进入系统！");
					} else if (num == 2) {
						pw.println("登录失败，密码错误！");
					} else if (num == 3) {
						pw.println("登录失败，账号错误！");
					}

				}

			} catch (Exception e) {
				System.out.println("服务器故障，关闭服务器");
				System.exit(1);
				e.printStackTrace();
			} finally {
				try {
					s.close();
				} catch (IOException e) {
					System.err.println("服务器故障，关闭失败！");
					e.printStackTrace();
				}
			}

		}
	}

	public static void main(String[] args) throws Exception {
		LoginServer ls = new LoginServer(new ServerSocket(9999));
		ls.start();

	}

}
